import {createRouter, createWebHistory} from 'vue-router'
import Login from '../views/Login.vue'

const clientRouters = [
    {
        path: '/',
        component: Login
    },
    {
        path: "/login",
        component: Login
    },
    {
        path: '/home',
        name: 'home',
        component: () => import('../views/Index.vue'),
        children: [
            {
                path: '',
                component: () => import('../views/home/Index.vue')
            },
            {
                path: 'sysRole/index',
                component: () => import('../views/home/sysRole/Index.vue')
            },
            {
                path: 'sysUser/index',
                component: () => import('../views/home/sysUser/Index.vue')
            },
            {
                path: 'sysUser/info',
                component: () => import('../views/home/userInfo/Index.vue')
            },
            {
                path: 'sysMenu/index',
                component: () => import('../views/home/sysMenu/Index.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: clientRouters
})

/*//定义一个路由接口
interface Route {
    path: string,
    component: string,
    name: string,
    parentName: string
}*/

//前置路由守卫
router.beforeEach((to, from, next) => {

    // 如果访问的是登录页面，并且localStorage中的sysUserToken存在
    let localStorageSysUserToken = localStorage.getItem("Authorization")
    if (to.path === '/login' && localStorageSysUserToken) {
        // 如果localStorage中的sysUserToken存在且访问了登录路由
        // 跳转到首页页面
        next({path: '/home'})
    } else if (to.path === '/login') {
        // 跳过登录路由/login
        next()
    } else if (!localStorageSysUserToken) {
        // 如果localStorage中的sysUserToken不存在，表示未登录
        // 跳转到登录页面
        next({path: '/login'})
    }

    // 其他正常情况，next()继续
    next()
})

export default router
